package com.cl.utility.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author liddhappy
 * @description token 工具类
 * @createTime 2022/11/21 22:51
 */
public class TokenUtils {
    //设置过期时间
    private static final long EXPIRE_TIME = 240 * 60 * 1000;
    //token秘钥
    private static final String TOKEN_SECRET = "f26e587c28064d0e855e72c0a6a0e618";
    private static final String USER_NAME = "userName";
    private static final String ADMIN_PERMISSION = "permission";

    public static String initBase64SECRET() {
        return GenerateUtils.BASE64Encoding(UUID.randomUUID().toString());
    }

    /**
     * @param secret 密钥
     * @param username 用户名
     * @param permission 权限
     * @return
     */
    public static String sign(String secret, String username, String permission) {
        String token = "";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(secret);
            //设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带username,permissions信息，生成签名
            return JWT.create()
                    .withHeader(header)
                    .withClaim(USER_NAME, username)
                    .withClaim(ADMIN_PERMISSION, permission)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 验证token
     *
     * @param secret  密钥
     * @param token
     * @return 通过true 否则false
     */
    public static boolean verify(String secret, String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return !isJwtExpired(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 解密token，返回一个map
     *
     * @param token
     * @return
     */
    public static String parseJWT(String token) {
        DecodedJWT decodeToken = JWT.decode(token);
        return decodeToken.getClaim(USER_NAME).asString();
    }

    /**
     * 判断token是否过期
     *
     * @param token
     * @return
     */
    public static boolean isJwtExpired(String token) {
        try {
            DecodedJWT decodeToken = JWT.decode(token);
            return decodeToken.getExpiresAt().before(new Date());
        } catch (Exception e) {
            return true;
        }
    }
}

